﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.DataSourcesFile;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.SystemUI;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.Output;
using ESRI.ArcGIS.NetworkAnalysis;
using ESRI.ArcGIS.NetworkAnalyst;
using System.IO;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.GeoAnalyst;
using ESRI.ArcGIS.SpatialAnalyst;


enum OperT
{
    AddNorthArrow,
    AddLineScale,
    AddLegend,
    NULL
}
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        #region 全局变量
        OperT m_CurOper;
        int flag;
        IMapDocument m_MapDocument;
        IGraphicsContainer pGraphicsContainer;
        IHookHelper helper = new HookHelperClass();
        #endregion

        public Form1()
        {
            InitializeComponent();
        }

        // 初始化
        private void Form1_Load(object sender, EventArgs e)
        {
            updateMap();
        }

       

        // 退出
        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        // 地图放大命令
        private void 放大ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            flag = 1;
        }

        // 地图缩小命令
        private void 缩小ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            flag = 2;
        }

        // 地图移动命令
        private void 移动ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            flag = 3;
        }


        // 同步布局视图
        private void axMapControl1_OnAfterDraw(object sender, IMapControlEvents2_OnAfterDrawEvent e)
        {
            IObjectCopy objectCopy = new ObjectCopyClass();
            object toCopyMap = axMapControl1.Map;
            object copiedMap = objectCopy.Copy(toCopyMap);
            object toOverwriteMap = axPageLayoutControl1.ActiveView.FocusMap;
            //传递数据()
            objectCopy.Overwrite(copiedMap, ref toOverwriteMap); axPageLayoutControl1.ActiveView.Refresh();
        }

        // 更新鹰眼地图显示范围
        private void axMapControl1_OnExtentUpdated(object sender, IMapControlEvents2_OnExtentUpdatedEvent e)
        {
            IEnvelope pEnv;
            pEnv = e.newEnvelope as IEnvelope;
            IGraphicsContainer pGraphicsContainer;
            IActiveView pActiveView;
            pGraphicsContainer = axMapControl2.Map as IGraphicsContainer;
            pActiveView = pGraphicsContainer as IActiveView;
            pGraphicsContainer.DeleteAllElements();//'获取矩形坐标
            IRectangleElement pRectangleEle;
            pRectangleEle = new RectangleElementClass();
            IElement pEle;
            pEle = pRectangleEle as IElement;
            pEle.Geometry = pEnv;

            IRgbColor pColor;
            pColor = new RgbColorClass();
            pColor.RGB = 255;
            pColor.Transparency = 255;
            ILineSymbol pOutline;
            pOutline = new SimpleLineSymbolClass();
            pOutline.Width = 1;
            pOutline.Color = pColor;
            pColor = new RgbColorClass();
            pColor.RGB = 255;
            pColor.Transparency = 0;

            IFillSymbol pFillSymbol;
            pFillSymbol = new SimpleFillSymbolClass();
            pFillSymbol.Color = pColor;
            pFillSymbol.Outline = pOutline;
            //‘构建矩形元素
            IFillShapeElement pFillshapeEle;
            pFillshapeEle = pEle as IFillShapeElement;
            pFillshapeEle.Symbol = pFillSymbol;
            pEle = pFillshapeEle as IElement;
            pGraphicsContainer.AddElement(pEle, 0);
            pActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
        }

        // 地图数据更新
        private void axMapControl1_OnMapReplaced(object sender, IMapControlEvents2_OnMapReplacedEvent e)
        {
            IMap pMap= axMapControl1.Map;
            axMapControl2.Map.ClearLayers();
            for (int i = pMap.LayerCount - 1; i > -1; i--)
            {
                axMapControl2.Map.AddLayer(pMap.get_Layer(i));
            }
        }

        // 地图点击事件
        private void axMapControl1_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            Console.Write(e.mapX.ToString() +","+e.mapY.ToString());


            // 放大
            if (flag == 1)
            {
                axMapControl1.Extent = axMapControl1.TrackRectangle();
                axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
            }
                // 缩小
            else if (flag == 2)
            {
                axMapControl1.Extent = axMapControl1.TrackRectangle();
                IEnvelope pEnv = axMapControl1.Extent;
                pEnv.Expand(2, 2, true);
                axMapControl1.Extent = pEnv;
                axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
            }
                // 移动
            else if (flag == 3)
                axMapControl1.Pan();
                // 空间查询
            else if (flag == 4)
            {
                axMapControl1.Map.ClearSelection();
                axMapControl1.CurrentTool = null;
                this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair;
                IGeometry pGeometry = this.axMapControl1.TrackPolygon();
                IFeatureLayer pFeatureLayer = this.axMapControl1.get_Layer(0) as IFeatureLayer;
                List<IFeature> pFList = this.GetSearchFeatures(pFeatureLayer, pGeometry);
                if (pFList.Count > 0)
                {
                    AttributesForm pAttributeForm = new AttributesForm();
                    pAttributeForm.dataGridView1.RowCount = pFList.Count + 1;
                    //设置边界风格
                    pAttributeForm.dataGridView1.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.Sunken;
                    //设置列数
                    pAttributeForm.dataGridView1.ColumnCount = pFList[0].Fields.FieldCount;
                    for (int m = 0; m < pFList[0].Fields.FieldCount; m++)
                    {
                        pAttributeForm.dataGridView1.Columns[m].HeaderText = pFList[0].Fields.get_Field(m).AliasName;
                    }
                    //遍历要素
                    for (int i = 0; i < pFList.Count; i++)
                    {
                        IFeature pFeature = pFList[i];
                        for (int j = 0; j < pFeature.Fields.FieldCount; j++)
                        {
                            pAttributeForm.dataGridView1[j, i].Value = pFeature.get_Value(j).ToString();
                        }
                    }
                    axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, null);
                    pAttributeForm.Show();
                }
                else {
                    MessageBox.Show("未查询到数据");
                }
            }
            else if (flag == 5)
            {
                axMapControl1.Map.ClearSelection();
                axMapControl1.CurrentTool = null;
                this.axMapControl1.MousePointer = esriControlsMousePointer.esriPointerCrosshair;

                IPoint poi = new PointClass();
                poi.X = e.mapX;
                poi.Y = e.mapY;

                IGeometry pGeometry = poi as IGeometry;
                IFeatureLayer pFeatureLayer = this.axMapControl1.get_Layer(8) as IFeatureLayer;
                List<IFeature> pFList = this.GetSearchFeatures(pFeatureLayer, pGeometry);
                if (pFList.Count > 0)
                {
                    IGeometry areaGeometry = pFList[0].Shape as IGeometry;
                    IFeatureLayer bikepFeatureLayer = this.axMapControl1.get_Layer(0) as IFeatureLayer;
                    List<IFeature> bikeresFList = this.GetSearchFeatures(bikepFeatureLayer, areaGeometry);
                    if (bikeresFList.Count > 0)
                    {
                        BikeAttributesForm BikeAttributesForm = new BikeAttributesForm();
                        BikeAttributesForm.label1.Text = "FID:" + bikeresFList[0].get_Value(0).ToString() + ";";
                        BikeAttributesForm.label2.Text = "行政区划名称:" + pFList[0].get_Value(3).ToString() + ";";
                        BikeAttributesForm.label3.Text = "单车数量:" + bikeresFList.Count.ToString() + "辆;";
                        BikeAttributesForm.label4.Text = "单车密度:" + (bikeresFList.Count / Convert.ToDouble(pFList[0].get_Value(8))).ToString("0.00") + "（辆/k㎡);";
                        BikeAttributesForm.Show();
                    }
                }
                else
                {
                    MessageBox.Show("未查询到数据");
                }

                axMapControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection, null, null);
                axMapControl1.Refresh();
            }
        }

        // 解析查询要素
        private List<IFeature> GetSearchFeatures(IFeatureLayer pFeatureLayer, IGeometry pGeometry)
        {
            try
            {
                List<IFeature> pFeatureList = new List<IFeature>();
                ISpatialFilter pSpatialFilter = new SpatialFilterClass();
                IQueryFilter pQueryFilter = pSpatialFilter as IQueryFilter;
                pSpatialFilter.Geometry = pGeometry;
                pSpatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                IFeatureCursor pFeatureCursor = pFeatureLayer.Search(pQueryFilter, false);
                IFeatureSelection pFeatureSelection = pFeatureLayer as IFeatureSelection;
                pFeatureSelection.SelectFeatures(pQueryFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
                IFeature pFeature = pFeatureCursor.NextFeature();
                while (pFeature != null)
                {
                    pFeatureList.Add(pFeature);
                    pFeature = pFeatureCursor.NextFeature();
                }
                return pFeatureList;
            }
            catch (Exception Err)
            {
                MessageBox.Show(Err.Message, "异常提示", MessageBoxButtons.OK, MessageBoxIcon.Question);
                return null;
            }
        }

        // 鼠标移动
        private void axMapControl1_OnMouseMove(object sender, IMapControlEvents2_OnMouseMoveEvent e)
        {
            if (e.button == 1)
            {
                IActiveView pAV = axMapControl1.ActiveView;
                IScreenDisplay pSD = pAV.ScreenDisplay;
                IPoint pPt = new PointClass();
                pPt.PutCoords(e.mapX, e.mapY);
                pSD.RotateMoveTo(pPt);
                pSD.RotateTimer();
            }
            scale.Text = "当前比例尺：1 :" + ((long)this.axMapControl1.MapScale).ToString();
            position.Text = " 鼠标位置：X = " + e.mapX.ToString() + " Y = " + e.mapY.ToString() + " " + this.axMapControl1.MapUnits.ToString().Substring(4);
        }

        // 鹰眼框选操作
        private void axMapControl2_OnMouseDown(object sender, IMapControlEvents2_OnMouseDownEvent e)
        {
            IEnvelope pEnv = axMapControl2.TrackRectangle();
            axMapControl1.Extent = pEnv;
            axMapControl1.Refresh();
        }

        //  添加指北针
        private void 指北针ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_CurOper = OperT.AddNorthArrow;
        }

        //  添加比例尺
        private void 比例尺ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_CurOper = OperT.AddLineScale;
        }

        private IRgbColor getRGB(int r, int g, int b)
        {
            IRgbColor pColor;
            pColor = new RgbColorClass();
            pColor.Red = r;
            pColor.Green = g;
            pColor.Blue = b;
            return pColor;
        }

        // 地图布局操作
        private void axPageLayoutControl1_OnMouseDown(object sender, IPageLayoutControlEvents_OnMouseDownEvent e)
        {
            // 指北针
            if (m_CurOper == OperT.AddNorthArrow)
            {
                IEnvelope pEnv = axPageLayoutControl1.TrackRectangle();
                IMapSurround pMapSurround;
                UID pID = new UIDClass();
                pID.Value = "esriCarto.MarkerNorthArrow";
                pMapSurround = CreateSurround(pID, pEnv, "North Arrow", axPageLayoutControl1.PageLayout);

            }

                // 比例尺
            else if(m_CurOper == OperT.AddLineScale)
            {
                IMapFrame pMapFrame = axPageLayoutControl1.GraphicsContainer.FindFrame(axPageLayoutControl1.ActiveView.FocusMap) as IMapFrame;
                UID uidScale = new UIDClass();
                uidScale.Value = "{6589F140-F7F7-11d2-B872-00600802E603}";
                IMapSurroundFrame pMapSurroundFrame = pMapFrame.CreateSurroundFrame(uidScale, null);
                IMapSurround pMapSurround = pMapSurroundFrame.MapSurround;
                IScaleBar pScaleBar = pMapSurround as IScaleBar;

                IEnvelope pEnv = axPageLayoutControl1.TrackRectangle();
                IElement pEle_ScaleBar = pMapSurroundFrame as IElement;
                pEle_ScaleBar.Geometry = pEnv;

                axPageLayoutControl1.GraphicsContainer.AddElement(pEle_ScaleBar, 0);
                axPageLayoutControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
            }

            //添加图例
            else if (m_CurOper == OperT.AddLegend)
            {
                IGraphicsContainer pLengendGraphicsContainer = axPageLayoutControl1.GraphicsContainer;
                IMapFrame mapFrame = (IMapFrame)pLengendGraphicsContainer.FindFrame(axPageLayoutControl1.ActiveView.FocusMap);
                if (mapFrame == null)
                    return;
                UID uID = new UID();
                uID.Value = "esriCarto.Legend";
                IMapSurroundFrame mapSurroundFrame = mapFrame.CreateSurroundFrame(uID, null);

                if (mapSurroundFrame == null)
                    return;
                if (mapSurroundFrame.MapSurround == null)
                    return;
                mapSurroundFrame.MapSurround.Name = "Legend";
                IEnvelope envelopeLegend = (IEnvelope)new Envelope();
                envelopeLegend.PutCoords(1, 1, 10, 10);
                IEnvelope pEnv = axPageLayoutControl1.TrackRectangle();
                IElement pLegendElement = (IElement)mapSurroundFrame;
                pLegendElement.Geometry = pEnv;

                axPageLayoutControl1.AddElement(pLegendElement, Type.Missing, Type.Missing, "Legend", 10);
                ILegend pLegend = (ILegend)mapSurroundFrame.MapSurround;
                pLegend.Name = "Legend";
                pLegend.Title = "图例";
                axPageLayoutControl1.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGraphics, null, null);
            }
            m_CurOper = OperT.NULL;

            
        }

        // 框选范围
        private IMapSurround CreateSurround(UID pID, IEnvelope pEnv, string strName, IPageLayout pPageLayout)
        {
            IGraphicsContainer pGraphicsC;
            IActiveView pActiveView; IMapFrame pMapFrame;
            IMapSurroundFrame pMapSFrame;
            IElement pElement; IMap pMap;
            pGraphicsC = (IGraphicsContainer)pPageLayout;
            pActiveView = (IActiveView)pPageLayout;
            pMap = pActiveView.FocusMap;
            pMapFrame = (IMapFrame)pGraphicsC.FindFrame(pMap);
            pMapSFrame = pMapFrame.CreateSurroundFrame(pID, null);
            pMapSFrame.MapSurround.Name = strName;
            pElement = (IElement)pMapSFrame;
            pElement.Geometry = pEnv;
            pElement.Activate(pActiveView.ScreenDisplay);
            ITrackCancel pTrack = null;
            pTrack = new CancelTracker();

            pElement.Draw(pActiveView.ScreenDisplay, pTrack);
            pGraphicsC.AddElement(pElement, 0);
            pActiveView.Refresh();
            return pMapSFrame.MapSurround;
        }

        // 空间查询
        private void 多边形查询ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            flag = 4;
        }

        // 清除查询结果
        private void 清除查询结果ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            flag = 0;
            IActiveView pActiveView = axMapControl1.ActiveView;
            for (int i = 0; i < axMapControl1.LayerCount; i++)
            {
                IFeatureLayer pFeaturelayer = axMapControl1.get_Layer(i) as IFeatureLayer;
                ClearSelectedMapFeatures(pActiveView, pFeaturelayer);
            }
        }

        // 清除查询
        public void ClearSelectedMapFeatures(ESRI.ArcGIS.Carto.IActiveView activeView, ESRI.ArcGIS.Carto.IFeatureLayer featureLayer)
        {
            if (activeView == null || featureLayer == null)
            {
                return;
            }
            ESRI.ArcGIS.Carto.IFeatureSelection featureSelection = featureLayer as ESRI.ArcGIS.Carto.IFeatureSelection;
            activeView.PartialRefresh(ESRI.ArcGIS.Carto.esriViewDrawPhase.esriViewGeoSelection, null, null);
            featureSelection.Clear();
        }

        // 导出图片
        private void 保存地图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                SaveFileDialog pSaveDialog = new SaveFileDialog();
                pSaveDialog.FileName = "";
                pSaveDialog.Filter = "JPG图片(*.JPG)|*.jpg|tif图片(*.tif)|*.tif|PDF文档(*.PDF)|*.pdf";
                if (pSaveDialog.ShowDialog() == DialogResult.OK)
                {
                    double iScreenDispalyResolution = this.axPageLayoutControl1.ActiveView.ScreenDisplay.DisplayTransformation.Resolution;
                    IExporter pExporter = null;
                    if (pSaveDialog.FilterIndex == 0)
                    {
                        pExporter = new JpegExporterClass();
                    }
                    else if (pSaveDialog.FilterIndex == 1)
                    {
                        pExporter = new TiffExporterClass();
                    }
                    else if (pSaveDialog.FilterIndex == 2)
                    {
                        pExporter = new PDFExporterClass();
                    }
                    pExporter.ExportFileName = pSaveDialog.FileName;
                    pExporter.Resolution = (short)iScreenDispalyResolution;
                    tagRECT deviceRect;
                    deviceRect.left = 0;
                    deviceRect.top = 0;
                    deviceRect.right = this.axPageLayoutControl1.ActiveView.ExportFrame.right * (300 / 96);
                    deviceRect.bottom = this.axPageLayoutControl1.ActiveView.ExportFrame.bottom * (300 / 96);
                    IEnvelope pDeviceEnvelope = new EnvelopeClass();
                    pDeviceEnvelope.PutCoords(deviceRect.left, deviceRect.bottom, deviceRect.right, deviceRect.top);
                    pExporter.PixelBounds = pDeviceEnvelope;
                    ITrackCancel pCancle = new CancelTrackerClass();
                    this.axPageLayoutControl1.ActiveView.Output(pExporter.StartExporting(), pExporter.Resolution, ref deviceRect, this.axPageLayoutControl1.ActiveView.Extent, pCancle);
                    Application.DoEvents();
                    pExporter.FinishExporting();
                    MessageBox.Show("输入成功，请查看。", "提示");
                }
            }
            catch (Exception Err)
            {
                MessageBox.Show(Err.Message, "输出图片", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }

        // 属性查询
        private void 属性查询ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ProToMap qf = new ProToMap(axMapControl1);
            qf.Show();
        }

        private void 全图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            axMapControl1.Extent = axMapControl1.FullExtent;
        }

        private void 图例ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            m_CurOper = OperT.AddLegend;
        }

      

        private void 获取单车数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            updateMap();
        }

        private void  updateMap(){


            GenerateRandomPoints(3200, 112.854624588542, 28.0537430119569, 113.202025895394, 28.4677692269713);

            ICommand command1 = new CreateNewDocument();
            command1.OnCreate(axMapControl1.Object);
            command1.OnClick();
            string sFilePath = System.Windows.Forms.Application.StartupPath + "\\长沙\\map.mxd";
            axMapControl1.LoadMxFile(sFilePath, 0, Type.Missing);

        }

        public void GenerateRandomPoints(int pointCount, double minX, double minY, double maxX, double maxY)
        {
            // 创建空间参考（以WGS84为例）
            ISpatialReference spatialRef = CreateSpatialReference(4326);

            // 创建工作空间
            string folderPath = System.Windows.Forms.Application.StartupPath + "\\长沙\\"; // 指定输出文件夹
            IWorkspace workspace = CreateShapefileWorkspace(folderPath);
            IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;

            // 删除已存在的Shapefile
            string shpPath = System.IO.Path.Combine(folderPath, "单车.shp");
            if (File.Exists(shpPath))
            {
                DeleteShapefile(folderPath, "单车");
            }

            // 创建点要素类（增加z字段）
        IFeatureClass featureClass = CreatePointFeatureClassWithZ(featureWorkspace, "单车", spatialRef);

        // 生成随机点
        Random rand = new Random();
        IFeatureBuffer featureBuffer;
        IFeatureCursor insertCursor = featureClass.Insert(true);

        try
        {
            for (int i = 0; i < pointCount; i++)
            {
                // 生成随机坐标
                double x = minX + (maxX - minX) * rand.NextDouble();
                double y = minY + (maxY - minY) * rand.NextDouble();
                double z = rand.NextDouble() * 100; // 生成0-100之间的随机z值

                // 创建点几何
                IPoint point = new PointClass();
                point.PutCoords(x, y);
                point.SpatialReference = spatialRef;

                // 创建要素并设置属性
                featureBuffer = featureClass.CreateFeatureBuffer();
                featureBuffer.Shape = point;
                featureBuffer.set_Value(featureBuffer.Fields.FindField("z"), z); // 设置z值
                insertCursor.InsertFeature(featureBuffer);
            }
            insertCursor.Flush();
        }
        finally
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(insertCursor);
        }
    }

    private ISpatialReference CreateSpatialReference(int wkid)
    {
        ISpatialReferenceFactory2 srFactory = new SpatialReferenceEnvironmentClass();
        return srFactory.CreateSpatialReference(wkid);
    }

    private IWorkspace CreateShapefileWorkspace(string folderPath)
    {
        IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactoryClass();
        return workspaceFactory.OpenFromFile(folderPath, 0);
    }

    private IFeatureClass CreatePointFeatureClassWithZ(IFeatureWorkspace workspace, string name, ISpatialReference spatialRef)
    {
        IFields fields = new FieldsClass();
        IFieldsEdit fieldsEdit = (IFieldsEdit)fields;

        // 1. 创建OID字段
        IField oidField = new FieldClass();
        IFieldEdit oidFieldEdit = (IFieldEdit)oidField;
        oidFieldEdit.Name_2 = "OID";
        oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID;
        fieldsEdit.AddField(oidField);

        // 2. 创建几何字段
        IField shapeField = new FieldClass();
        IFieldEdit shapeFieldEdit = (IFieldEdit)shapeField;
        shapeFieldEdit.Name_2 = "Shape";
        shapeFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry;

        IGeometryDef geometryDef = new GeometryDefClass();
        IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef;
        geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint;
        geometryDefEdit.SpatialReference_2 = spatialRef;
        shapeFieldEdit.GeometryDef_2 = geometryDef;

        fieldsEdit.AddField(shapeField);

        // 3. 创建z字段（双精度）
        IField zField = new FieldClass();
        IFieldEdit zFieldEdit = (IFieldEdit)zField;
        zFieldEdit.Name_2 = "z";
        zFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
        fieldsEdit.AddField(zField);

        // 创建要素类
        return workspace.CreateFeatureClass(name, fields, null, null, esriFeatureType.esriFTSimple, "Shape", "");
    }

    private void DeleteShapefile(string folderPath, string name)
    {
        foreach (string extension in new[] { ".shp", ".shx", ".dbf", ".prj", ".sbn", ".sbx" })
        {
            string filePath = System.IO.Path.Combine(folderPath, name + extension);
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }
        }
    }


        private void 分布密度分析ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IFeatureLayer pFeatureLayer = this.axMapControl1.get_Layer(0) as IFeatureLayer;
            IFeatureClass feclass = pFeatureLayer.FeatureClass;
            IRaster resIRaster = DensityAnalyst(feclass, "z", 1.38861757196486E-03, 1.15718130997071E-02);
            Random rd = new Random();
            string uid = rd.Next(100000, 1000000).ToString();
            string rasterPath = System.Windows.Forms.Application.StartupPath + "\\image";

            //着色                
            IRasterLayer pRasterLayer = new RasterLayer() as IRasterLayer;
            pRasterLayer.Name = "mdanalysic" + uid;
            ConvertRasterToRsDataset(rasterPath, ref resIRaster, "mdanalysic" + uid);
            pRasterLayer = SetRsLayerClassifiedColor(resIRaster);
            axMapControl1.AddLayer(pRasterLayer, 9);
            axMapControl1.Refresh();

        }

        private void 点击选择区县ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            flag = 5;
        }


        public IRaster DensityAnalyst(IFeatureClass pFeatureClass, string pFieldName, double pCellSize, double pRadius)
        {
            //辅助对象,设置密度分析时候的参数
            IFeatureClassDescriptor pFDescr = new FeatureClassDescriptorClass();
            pFDescr.Create(pFeatureClass, null, pFieldName);
            IDensityOp pDensityOp = new RasterDensityOpClass();
            //设置环境
            IRasterAnalysisEnvironment pEnv = pDensityOp as IRasterAnalysisEnvironment;
            object object_cellSize = (System.Object)pCellSize;
            pEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref object_cellSize);
            System.Double double_radio_dis = pRadius;
            object object_radio_dis = (System.Object)double_radio_dis;
            object Missing = Type.Missing;
            //核函数密度制图方法生成栅格数据
            IRaster pRaster = pDensityOp.KernelDensity(pFDescr as IGeoDataset, ref object_radio_dis, ref Missing) as IRaster;
            return pRaster;
        }

        private void ConvertRasterToRsDataset(String sPath, ref IRaster pRaster, String sOutName)
        {
            //try
            //{
            IWorkspaceFactory pWSF = new RasterWorkspaceFactory() as IWorkspaceFactory;
            if (pWSF.IsWorkspace(sPath) == false)
            {
                return;
            }

            IWorkspace pRWS = pWSF.OpenFromFile(sPath, 0);

            if (File.Exists(sPath + "\\" + sOutName + ".img") == true)
            {
                File.Delete(sPath + "\\" + sOutName + ".img");
            }


            IRasterBandCollection pRasBandCol = (IRasterBandCollection)pRaster;

            IDataset pDS = pRasBandCol.SaveAs(sOutName + ".img", pRWS, "IMAGINE Image");
            ITemporaryDataset pRsGeo = (ITemporaryDataset)pDS;
            if (pRsGeo.IsTemporary())
            {
                pRsGeo.MakePermanent();
            }
            //}

            //catch (Exception ex)
            //{
            //    MessageBox.Show("2" + ex.Message);
            //}
        }

        private IRasterLayer SetRsLayerClassifiedColor(IRaster pRaster)
        {
            //获得栅格统计数值 必须先统计出结果
            IRasterBandCollection pRsBandCol = (IRasterBandCollection)pRaster;
            IRasterBand pRsBand = pRsBandCol.Item(0);
            pRsBand.ComputeStatsAndHist();
            IRasterStatistics pRasterStatistic = pRsBand.Statistics;
            double dMaxValue = pRasterStatistic.Maximum;
            double dMinValue = pRasterStatistic.Minimum;

            IRasterClassifyColorRampRenderer pClassRen = new RasterClassifyColorRampRenderer() as IRasterClassifyColorRampRenderer;
            IRasterRenderer pRasRen = (IRasterRenderer)pClassRen;
            //Set raster for the render and update
            pRasRen.Raster = pRaster;
            pClassRen.ClassCount = 9;
            pRasRen.Update();
            //Create a color ramp to use
            //定义起点和终点颜色
            IColor pFromColor = new RgbColorClass();
            IRgbColor pRgbColor = (IRgbColor)pFromColor;
            pRgbColor.Red = 0;
            pRgbColor.Green = 255;
            pRgbColor.Blue = 0;
            IColor pToColor = new RgbColorClass();
            pRgbColor = (IRgbColor)pToColor;
            pRgbColor.Red = 255;
            pRgbColor.Green = 0;
            pRgbColor.Blue = 0;
            //创建颜色分级
            IAlgorithmicColorRamp pRamp = new AlgorithmicColorRampClass();
            pRamp.Size = 9;
            pRamp.FromColor = pFromColor;
            pRamp.ToColor = pToColor;
            bool ok = true;
            pRamp.CreateRamp(out ok);

            //Create symbol for the classes
            IFillSymbol pFSymbol = new SimpleFillSymbolClass();
            double LabelValue = Convert.ToDouble((dMaxValue - dMinValue) / 9);

            for (int i = 0; i < pClassRen.ClassCount; i++)
            {
                pFSymbol.Color = pRamp.get_Color(i);
                pClassRen.set_Symbol(i, (ISymbol)pFSymbol);
                double h1 = (LabelValue * i) + dMinValue;
                double h2 = (LabelValue * (i + 1)) + dMinValue;
                pClassRen.set_Label(i, h1.ToString() + "-" + h2.ToString());
            }

            //Update the renderer and plug into layer
            pRasRen.Update();
            IRasterLayer pRLayer = new RasterLayer() as IRasterLayer;
            pRLayer.CreateFromRaster(pRaster);
            pRLayer.Renderer = (IRasterRenderer)pClassRen;
            return pRLayer;
        }

    }
}